package com.andy.controller;


import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.andy.service.IExamUserService;
import com.andy.utils.MD5Utils;
import com.andy.vo.ExamUserVO;

@Controller
public class LoginController {
	
	@Autowired
	private IExamUserService examUserService;
	
	// 进入登录页面　
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String toLogin() {
		return "login/login";
	}
	
	//　进行登录
	// value object
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(ExamUserVO vo, HttpSession session) {
		if (vo != null ) {
			ExamUserVO resultVO = examUserService.getUserById(vo.getUserId());
			if (resultVO != null) {
				if (vo.getPassword() != null) {
					String encodePassword = MD5Utils.GetMD5Code(vo.getPassword());
					// 密码正确的情况
					Date currentTime = null;
					Calendar currentTimecalendar = Calendar.getInstance();		// 创建日历对象
					currentTimecalendar.setTime(new Date());	//　初始化时间　new Date() -> 46
					
					currentTimecalendar.add(Calendar.MINUTE, -5);	// 减５分		// 41
					
					currentTime = currentTimecalendar.getTime();	// currentTime -> 41
					
					System.out.println(currentTime + "-------------------" + new Date());
					if (resultVO.getLastLockTime().before(currentTime)) {	// resultVO.getLastLockTime() -> 39	before Ａ在Ｂ的前面，   after　Ａ在Ｂ的后面
						// 不在锁定时间范围内
						
						System.out.println("不在锁定时间范围内");
						if (encodePassword.equals(resultVO.getPassword())) {
							// 登录成功时清０
							resultVO.setLoginFailCount(0);
							examUserService.updateUserLoginFailCount(resultVO);
							session.setAttribute("examUser", resultVO);
							return "redirect:/index/index";
						} else {
							resultVO.setLoginFailCount(resultVO.getLoginFailCount() + 1);
							if (resultVO.getLoginFailCount() == 3) {
								resultVO.setLoginFailCount(0);
								resultVO.setLastLockTime(new Date());
								examUserService.updateUserLastLockTime(resultVO);
							}
							examUserService.updateUserLoginFailCount(resultVO);
						}
					} else {
						// 锁定时间范围内
						System.out.println("目前账号被锁定，无法登录，请稍等５分钟。");
					}
				}
			}
		}
		return "login/login";
	}
	
	@RequestMapping(value = "/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("examUser");
		return "redirect:/login";
	}

}
